<template>
	<view class="container">
		<camera device-position="back" flash="auto" style="width: 100%; height: 500upx;">
			<cover-image src="https://aip.baidubce.com/rest/2.0/ocr/v1/idcard" class="scan-img"></cover-image>
		</camera>
		<view class="photo">
			<view class="album"><uni-icons type="image" color="#fff" size="30" @click="openAlbum"></uni-icons></view>
			<view><uni-icons type="camera-filled" color="#fff" size="80" @click="takePhoto"></uni-icons></view>
		</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				apiKey: 'mGV8hujO5AFmhoIvqk1wbsjx',
				SecretKey: 'G10vQFzGWcePitZ2wc555N6uat1tu4A8',
			}
		},
		onLoad() {
			// 每次加载页面的时候就获取token
			this.getAccessToken();
		},
		methods: {
			//打开相册
			openAlbum() {
				uni.showLoading({
					title: '正在获取图片...'
				})
				let that = this
				uni.chooseImage({
					count: 1, // 默认9  
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
					sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有  
					success: res => {
						uni.hideLoading()
						let tempFilePaths = res.tempFilePaths[0]
						// 图片转 base64
						uni.getFileSystemManager().readFile({
							filePath: tempFilePaths, //选择图片返回的相对路径  
							encoding: 'base64', //编码格式  
							success: v=> { //成功的回调  
								let base64String =  v.data 
								that.getIdInfo(base64String)
							 }  
						}) 
						
						
					}
				})
			},
			// 点击拍照
			takePhoto() {
				uni.showLoading({
					title: '正在获取图片...'
				})
				let that = this
				const ctx = uni.createCameraContext()
				ctx.takePhoto({
					quality: 'normal',
					success: res => {
						uni.hideLoading()
						let base64String =
							`${wx.getFileSystemManager().readFileSync(res.tempImagePath, "base64")}`
						that.getIdInfo(base64String)
					}
				})
			},
			// access_token 有效期为 2592000 秒 / 30天，获取token
			getAccessToken() {
				uni.showLoading({
					title: '正在获取令牌...'
				})
				let that = this
				uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token',
					method: 'POST',
					data: {
						grant_type: 'client_credentials',
						client_id: that.apiKey, // 在百度智能云那边创建一个应用后可以获取
						client_secret: that.SecretKey // 在百度智能云那边创建一个应用后可以获取
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: res => {
						uni.hideLoading()
						uni.setStorageSync('accessToken', res.data.access_token)
					},
					fail(e) {
					 uni.hideLoading()
						uni.showToast({
							title: '连接服务出错，请稍后再试!'
						})
 
					}
 
				});
			},
			getIdInfo(base64String) {
				let accessToken = uni.getStorageSync('accessToken')
				uni.showLoading({
					title: '正在解析...'
				})
				// 开始识别
				uni.request({
					url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + accessToken,
					method: 'POST',
					data: {
						image: base64String,
						id_card_side: 'front' // 身份证 正反面  front：身份证含照片的一面  back：身份证带国徽的一面
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: res => {
						uni.hideLoading()
						console.log("res.data身份信息", res.data.words_result)
						uni.showToast({
							title: res.data.words_result.公民身份号码
								.words,
							duration: 20000
						});
						
						const xxdata = JSON.stringify(res.data.words_result)
						const codedata = encodeURIComponent(xxdata)
						uni.navigateTo({
							url:"/pages/chenke/chenke?codedata="+codedata
						})
					},
					fail(e) {
						uni.hideLoading()
						uni.showToast({
							title: '连接服务出错，请稍后再试!'
						})
 
					}
 
				});
			}
 
		}
	}
</script>
 
<style>
	.container {
		background-color: #aaa;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}
 
	.scan-img {
		width: 100%;
		height: 500upx;
	}
 
	.photo {
		position: absolute;
		bottom: 0;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	/* 相册按钮使用绝对定位，保证相机按钮居中显示 */
	.album {
		position: absolute;
		left: 50px;
	}
</style>
